package thread.producerconsumer;

/**
 * 生产者  和 消费者
 */
public class Shop {

  volatile int sales = 1000;

  int speed = 1;

  public void product() throws InterruptedException {
    while (true) {
      synchronized (this) {
        //防止爆仓
        while (sales + speed > 1000) {
          wait();
        }
        //0库存终止补仓
        if (sales == 0) break;
        sales += speed;
        System.out.println(String.format("生产%s,剩余%s库存", speed, sales));
      }
    }
  }

  public void consumer() {
    while (true) {
      synchronized (this) {
        int i = sales - speed * 2;
        //0库存终止消费
        if (i <= 0) {
          sales = 0;
          System.out.println(String.format("消费%s,剩余%s库存", speed * 2 + i, sales));
          break;
        }
        sales = i;
        System.out.println(String.format("消费%s,剩余%s库存", speed * 2, sales));
        //唤醒补仓操作
        notifyAll();
      }
    }
  }

  public static void main(String[] args) {
    Shop shop = new Shop();
    Thread product = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          shop.product();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });

    Thread consumer = new Thread(new Runnable() {
      @Override
      public void run() {
        shop.consumer();
      }
    });
    product.start();
    consumer.start();
  }

}
